package chainofresponsibility.twoway;

import java.util.ArrayList;

/**
 * 链
 */
public class FilterChain implements Filter {
    // 记录原型链下一个
    public ArrayList<FilterChain> next = new ArrayList<>();

    // 存放所有的过滤器
    private ArrayList<Filter> list = new ArrayList<>();

    // 添加过滤器
    public FilterChain add(Filter filter){
        // 存储下一个链
        if(filter instanceof FilterChain){
            next.add((FilterChain)filter);
        }

        list.add(filter);
        return this;
    }

    // 控制读取
    private int flgCursor = 0;

    // 是否可以读取下一个
    private boolean hasNext(){
        return flgCursor < list.size();
    }

    // 获取下一个链
    public FilterChain getNextChain(){
        FilterChain f = next.get(0);
        next.remove(0);
        return f;
    }

    @Override
    public boolean doFilter(Request request, Response response, FilterChain filterChain) {
        if(hasNext()){
          return list.get(flgCursor++).doFilter(request, response, filterChain);
        }else{
            return false;
        }
    }
}
